#!/bin/bash

# 课程中心微服务端到端测试运行脚本 (Linux/Mac版本)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 显示帮助信息
show_help() {
    echo -e "${GREEN}课程中心微服务端到端测试运行脚本${NC}"
    echo ""
    echo -e "${YELLOW}用法:${NC}"
    echo "  ./run-e2e-tests.sh [选项]"
    echo ""
    echo -e "${YELLOW}选项:${NC}"
    echo "  -m, --mode <模式>     测试运行模式: interactive, run, headless"
    echo "  -s, --spec <文件>     运行特定的测试文件"
    echo "  -h, --headless        运行无头模式测试"
    echo "  --help               显示此帮助信息"
    echo ""
    echo -e "${YELLOW}示例:${NC}"
    echo "  ./run-e2e-tests.sh                    # 交互模式"
    echo "  ./run-e2e-tests.sh -m run             # 运行所有测试"
    echo "  ./run-e2e-tests.sh -h                 # 无头模式"
    echo "  ./run-e2e-tests.sh -s auth.cy.js      # 运行特定测试"
    exit 0
}

# 解析命令行参数
MODE="interactive"
SPEC=""
HEADLESS=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -m|--mode)
            MODE="$2"
            shift 2
            ;;
        -s|--spec)
            SPEC="$2"
            shift 2
            ;;
        -h|--headless)
            HEADLESS=true
            shift
            ;;
        --help)
            show_help
            ;;
        *)
            echo -e "${RED}[错误] 未知参数: $1${NC}"
            show_help
            ;;
    esac
done

echo -e "${CYAN}================================================${NC}"
echo -e "${CYAN}课程中心微服务端到端测试运行脚本${NC}"
echo -e "${CYAN}================================================${NC}"

# 检查操作系统
OS=$(uname -s)
echo -e "${GREEN}检测到操作系统: $OS${NC}"

# 检查Node.js环境
echo -e "${GREEN}检查Node.js环境...${NC}"
if ! command -v node &> /dev/null; then
    echo -e "${RED}[错误] 未找到Node.js，请先安装Node.js${NC}"
    echo -e "${YELLOW}安装方法:${NC}"
    if [[ "$OS" == "Darwin" ]]; then
        echo "  brew install node"
    elif [[ "$OS" == "Linux" ]]; then
        echo "  sudo apt-get install nodejs npm  # Ubuntu/Debian"
        echo "  sudo yum install nodejs npm      # CentOS/RHEL"
    fi
    exit 1
fi

NODE_VERSION=$(node --version)
echo -e "${GREEN}[信息] Node.js版本: $NODE_VERSION${NC}"

# 检查npm环境
echo -e "${GREEN}检查npm环境...${NC}"
if ! command -v npm &> /dev/null; then
    echo -e "${RED}[错误] 未找到npm，请检查Node.js安装${NC}"
    exit 1
fi

NPM_VERSION=$(npm --version)
echo -e "${GREEN}[信息] npm版本: $NPM_VERSION${NC}"

# 进入前端目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRONTEND_DIR="$(dirname "$SCRIPT_DIR")"
cd "$FRONTEND_DIR"
echo -e "${GREEN}当前工作目录: $(pwd)${NC}"

# 检查必要文件
if [[ ! -f "package.json" ]]; then
    echo -e "${RED}[错误] 未找到package.json文件${NC}"
    exit 1
fi

if [[ ! -f "cypress.config.js" ]]; then
    echo -e "${RED}[错误] 未找到cypress.config.js文件${NC}"
    exit 1
fi

echo ""
echo -e "${CYAN}================================================${NC}"
echo -e "${CYAN}第一步: 检查依赖项${NC}"
echo -e "${CYAN}================================================${NC}"

# 检查Cypress是否已安装
if npm list cypress &> /dev/null; then
    echo -e "${GREEN}[信息] Cypress已安装${NC}"
else
    echo -e "${YELLOW}[警告] Cypress未安装，正在安装...${NC}"
    npm install cypress --save-dev
    if [[ $? -ne 0 ]]; then
        echo -e "${RED}[错误] Cypress安装失败${NC}"
        exit 1
    fi
    echo -e "${GREEN}[信息] Cypress安装完成${NC}"
fi

echo ""
echo -e "${CYAN}================================================${NC}"
echo -e "${CYAN}第二步: 检查后端服务状态${NC}"
echo -e "${CYAN}================================================${NC}"

# 检查curl命令
if ! command -v curl &> /dev/null; then
    echo -e "${YELLOW}[警告] 未找到curl命令，跳过服务状态检查${NC}"
else
    # 检查API网关
    echo -e "${GREEN}检查API网关 (http://localhost:8080)...${NC}"
    if curl -s --connect-timeout 5 http://localhost:8080/actuator/health &> /dev/null; then
        echo -e "${GREEN}[信息] API网关运行正常${NC}"
    else
        echo -e "${YELLOW}[警告] API网关似乎未运行，请确保后端服务已启动${NC}"
        echo ""
        echo -e "${YELLOW}启动后端服务的方法:${NC}"
        echo "1. 进入后端目录: cd ../backend/microservices"
        echo "2. 运行: docker-compose up -d"
        echo "或者运行: ./start-all-services.sh"
        echo ""
        
        read -p "是否继续运行测试? (y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo -e "${YELLOW}测试已取消${NC}"
            exit 1
        fi
    fi
    
    # 检查各个微服务
    services=(
        "用户管理服务:8082"
        "课程管理服务:8083"
        "学习进度服务:8084"
    )
    
    for service in "${services[@]}"; do
        IFS=':' read -r name port <<< "$service"
        echo -e "${GREEN}检查$name (http://localhost:$port)...${NC}"
        if curl -s --connect-timeout 3 http://localhost:$port/actuator/health &> /dev/null; then
            echo -e "${GREEN}[信息] $name运行正常${NC}"
        else
            echo -e "${YELLOW}[警告] $name可能未运行${NC}"
        fi
    done
fi

echo ""
echo -e "${CYAN}================================================${NC}"
echo -e "${CYAN}第三步: 运行测试${NC}"
echo -e "${CYAN}================================================${NC}"

# 如果指定了无头模式
if [[ "$HEADLESS" == true ]]; then
    MODE="headless"
fi

# 运行测试的函数
run_specific_test() {
    local test_file="$1"
    local mode="$2"
    
    if [[ "$mode" == "headless" ]]; then
        npx cypress run --headless --spec "cypress/e2e/$test_file"
    else
        npx cypress run --spec "cypress/e2e/$test_file"
    fi
}

run_all_tests() {
    local mode="$1"
    
    echo -e "${GREEN}[信息] 运行所有端到端测试...${NC}"
    echo ""
    echo -e "${YELLOW}测试执行顺序:${NC}"
    echo "1. 用户认证测试"
    echo "2. 课程管理测试"
    echo "3. 课程内容测试"
    echo "4. 练习模块测试"
    echo "5. 用户中心测试"
    echo "6. 学习记录测试"
    echo ""
    
    test_files=(
        "auth.cy.js"
        "course.cy.js"
        "course_content.cy.js"
        "exercise.cy.js"
        "user_center_enhanced.cy.js"
        "learning_records.cy.js"
    )
    
    total_tests=${#test_files[@]}
    current_test=1
    
    for test_file in "${test_files[@]}"; do
        echo -e "${GREEN}[$current_test/$total_tests] 运行 $test_file...${NC}"
        if [[ "$mode" == "headless" ]]; then
            npx cypress run --headless --spec "cypress/e2e/$test_file" --reporter json --reporter-options "toConsole=false"
        else
            npx cypress run --spec "cypress/e2e/$test_file" --reporter json --reporter-options "toConsole=false"
        fi
        ((current_test++))
    done
}

# 根据模式运行测试
case "$MODE" in
    "headless")
        echo -e "${GREEN}[信息] 运行无头模式测试...${NC}"
        if [[ -n "$SPEC" ]]; then
            run_specific_test "$SPEC" "headless"
        else
            run_all_tests "headless"
        fi
        ;;
    "run")
        echo -e "${GREEN}[信息] 运行测试...${NC}"
        if [[ -n "$SPEC" ]]; then
            run_specific_test "$SPEC" "run"
        else
            run_all_tests "run"
        fi
        ;;
    "interactive")
        echo -e "${GREEN}[信息] 打开Cypress测试界面...${NC}"
        npx cypress open
        ;;
    *)
        # 交互模式选择
        echo -e "${YELLOW}请选择测试运行模式:${NC}"
        echo "1. 无头模式 (headless) - 适合CI/CD"
        echo "2. 有界面模式 (headed) - 适合调试"
        echo "3. 交互模式 - 打开Cypress测试界面"
        echo "4. 运行特定测试文件"
        echo "5. 运行所有测试 (推荐)"
        
        read -p "请输入选择 (1-5): " choice
        
        case "$choice" in
            "1")
                run_all_tests "headless"
                ;;
            "2")
                run_all_tests "run"
                ;;
            "3")
                npx cypress open
                ;;
            "4")
                echo ""
                echo -e "${YELLOW}可用的测试文件:${NC}"
                echo "1. auth.cy.js - 用户认证测试"
                echo "2. course.cy.js - 课程管理测试"
                echo "3. exercise.cy.js - 练习模块测试"
                echo "4. user_center.cy.js - 用户中心测试"
                echo "5. user_password_change.cy.js - 密码修改测试"
                echo "6. course_inside.cy.js - 课程内部测试"
                echo "7. learning_records.cy.js - 学习记录测试 (新)"
                echo "8. user_center_enhanced.cy.js - 增强用户中心测试 (新)"
                echo "9. course_content.cy.js - 课程内容测试 (新)"
                
                read -p "请选择要运行的测试文件编号: " file_choice
                
                case "$file_choice" in
                    "1") run_specific_test "auth.cy.js" "run" ;;
                    "2") run_specific_test "course.cy.js" "run" ;;
                    "3") run_specific_test "exercise.cy.js" "run" ;;
                    "4") run_specific_test "user_center.cy.js" "run" ;;
                    "5") run_specific_test "user_password_change.cy.js" "run" ;;
                    "6") run_specific_test "course_inside.cy.js" "run" ;;
                    "7") run_specific_test "learning_records.cy.js" "run" ;;
                    "8") run_specific_test "user_center_enhanced.cy.js" "run" ;;
                    "9") run_specific_test "course_content.cy.js" "run" ;;
                    *) echo -e "${RED}[错误] 无效的选择${NC}" ;;
                esac
                ;;
            "5")
                run_all_tests "run"
                ;;
            *)
                echo -e "${RED}[错误] 无效的选择${NC}"
                ;;
        esac
        ;;
esac

echo ""
echo -e "${CYAN}================================================${NC}"
echo -e "${CYAN}测试完成${NC}"
echo -e "${CYAN}================================================${NC}"

# 检查测试结果
if [[ -d "cypress/results" ]]; then
    echo -e "${GREEN}[信息] 测试结果已保存到 cypress/results 目录${NC}"
fi

if [[ -d "cypress/screenshots" ]]; then
    echo -e "${GREEN}[信息] 测试截图已保存到 cypress/screenshots 目录${NC}"
fi

if [[ -d "cypress/videos" ]]; then
    echo -e "${GREEN}[信息] 测试视频已保存到 cypress/videos 目录${NC}"
fi

echo ""
echo -e "${GREEN}[信息] 端到端测试执行完成${NC}"
echo -e "${YELLOW}[提示] 如果测试失败，请检查:${NC}"
echo "  1. 后端微服务是否正常运行"
echo "  2. 数据库是否已正确初始化"
echo "  3. 测试数据是否存在"
echo "  4. 网络连接是否正常"
echo ""
